package com.Lyoto.NetNotify.Notifier.impl;

import com.Lyoto.NetNotify.Constraint.NetConfig;
import com.Lyoto.NetNotify.Handler.PushRegistrar;
import com.Lyoto.NetNotify.Handler.impl.EmailPusher;
import com.Lyoto.NetNotify.Handler.impl.WechatPush;
import com.Lyoto.NetNotify.NetChecks.Checker;
import com.Lyoto.NetNotify.Notifier.Notify;
import com.Lyoto.NetNotify.Utils.NetUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-09-19 17:55
 * @Version
 **/
@Slf4j
public class NetworkNotify implements Notify {
    Checker checker;
    private static volatile NetworkNotify notify;
    private final ConcurrentLinkedQueue<PushRegistrar> registrars = new ConcurrentLinkedQueue<>();

    public NetworkNotify(Checker checker) {
        this.checker = checker;
        notifyOrgInitialization();
    }

    private NetworkNotify() {
    }
    @Override
    public void notifyOrg() {
        doNotify();
    }

    private void notifyOrgInitialization() {
        NetConfig.setCurrentIp();
        this.addPushers(new WechatPush(),new EmailPusher());
       if(NetConfig.getIp() != null && !NetConfig.getIp().isEmpty()){
           log.info("启动加载项|初始化推送ip");
           this.notifyOrg();
       }
    }

    @Override
    public void notifyChangeIp() {
        try {
            if (checker.isIpChanging()) {
                NetConfig.setIp(NetUtil.getCurrentIp());
                notifyOrg();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Notify addPusher(PushRegistrar registrar) {
        registrars.add(registrar);
        return this;
    }



    public static NetworkNotify singletonInstance(Checker checker) {
        if (notify == null) {
            synchronized (NetworkNotify.class) {
                if (notify == null) {
                    notify = new NetworkNotify(checker);
                    log.info("IPNotify装配|Notify创建实例->{}", notify);
                }
            }
        }
        return notify;
    }

    protected void doNotify() {
        log.info("IP信息推送|正在推送IP到{}个推送方",registrars.size());
        registrars.forEach(PushRegistrar::pushOn);
    }

}
